package file;

import com.sun.jna.Platform;
import enums.FFmpegCodeEnum;
import exception.FFmpegException;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class Pid {

    public static String pid(String args) throws IOException {
        if (Platform.isWindows()) {
            return null;
        }
        String[] shell = {"/bin/bash", "-c", "ps ax | grep -i '" + args + "' | grep -v grep | awk '{print $1}'"};
        return exec(shell);
    }

    public static void killPid(String pid) throws IOException {
        if (Platform.isWindows()) {
            return;
        }
        String[] shell = {"/bin/bash", "-c", "ps ax | grep -i " + pid + " | grep -v grep | awk '{print $5}'"};
        String processName = exec(shell);
        if (StringUtils.isNotBlank(processName) && processName.contains("ffmpeg")) {
            Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", "kill -9 " + pid});
        }
    }

    private static String exec(String[] shell) throws IOException {
        Process exec = Runtime.getRuntime().exec(shell);
        exec.getOutputStream().close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while (StringUtils.isNotBlank(line = reader.readLine())) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    public static void killPids(List<String> pids) {
        if (pids == null) {
            return;
        }
        pids.forEach(pid -> {
            try {
                killPid(pid);
            } catch (IOException e) {
                throw new FFmpegException(FFmpegCodeEnum.FFMPEG_CLOSE_ERROR);
            }
        });
    }
}
